/*
 *
 * Copyright (c) 2021
 * User:Dybala
 * File:UserLoginService.java
 * Date:2021/11/12 20:16:12
 */

package com.service;

import com.dao.UserDao;
import com.pojo.Message;
import com.pojo.User;
import com.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserLoginService {
    @Autowired
    UserDao dao;
    @Autowired
    redisService server;
    public Message Login(String email, String pwd,String token){
        //首先判断是不是重复登录了
        String key="sys:user:token" + token;
        String str = server.get(key);
        Message res=new Message();
        String sc = "";
        if(token!=null){
            sc= JwtUtils.getEmail(token);
        }

        //如果redis中有数据并且登录的是同一个账号
        if(str!=null&&email.equals(sc)){
            res.setFlag(250);
            res.setMsg("请不要重复登录，直接进入主页即可");
            return res;
        }

        /**
         * 判断是否连续输入三次密码
         */
        String k="login"+email;
        String s = server.get(k);
        if(s==null){
            server.set(k,"1");
        }else{
            int i = Integer.parseInt(s);
            if(i>=6){
                res.setFlag(350);
                res.setMsg("请稍后重试");
                return res;
            }
            server.set(k,(i+1)+"");
        }
        server.expire(k,JwtUtils.EXPIRE_TIME/3);
        User user=null;
        user=dao.queryByEmailAndPwd(email,pwd);
        if(user==null){
            res.setFlag(400);
            res.setMsg("邮箱或密码错误");
        }else{
            //设置redis和token
            String sign = JwtUtils.sign(email);
            String tokenKey = "sys:user:token" + sign;
            server.set(tokenKey,sign);
            server.expire(tokenKey,JwtUtils.EXPIRE_TIME*2);
            server.del(k);
            res.setFlag(200);
            res.setMsg(sign);
        }
        return res;
    }
}
